package org.jflame.devAide.plugin;

import org.jflame.devAide.util.ResourceUtils;
import org.jflame.devAide.util.UIUtils;
import org.jflame.fx.util.FxUtils;

import java.io.Closeable;
import java.io.IOException;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.image.ImageView;

/**
 * 内部插件实现类，作为一个通用插件类使用
 * 
 * @author charles.zhang
 */
public class InnerPlugin implements ToolPlugin {

    private PluginInfo pluginInfo;
    private Object controller;

    public InnerPlugin(PluginInfo pluginInfo) {
        this(pluginInfo, null);
    }

    /**
     * 构造函数
     * 
     * @param pluginInfo 插件信息PluginInfo
     * @param controller 关联的控件类
     */
    public InnerPlugin(PluginInfo pluginInfo, Object controller) {
        if (pluginInfo.getFxml() == null) {
            throw new IllegalArgumentException("InnerPlugin插件必须指定FXML");
        }
        this.pluginInfo = pluginInfo;
        this.controller = controller;
    }

    /**
     * 使用指定的fxml文件生成插件Node
     */
    @Override
    public Node getContent() {
        Node pluginNode = null;
        if (controller == null) {
            FXMLLoader loader = FxUtils.createFXMLLoader(pluginInfo.getFxml(), ResourceUtils.getResourceBundle());
            try {
                pluginNode = loader.load();
            } catch (IOException e) {
                throw new IllegalStateException("从FXML加载界面失败", e);
            }
            controller = loader.getController();
        } else {
            pluginNode = FxUtils.loadFXML(pluginInfo.getFxml(), controller, ResourceUtils.getResourceBundle());
        }
        return pluginNode;
    }

    @Override
    public Node getIcon(double size) {
        // @开头为内置FontAwesome字体图标
        String icon = getPluginInfo().getIcon();
        if (icon != null) {
            if (icon.charAt(0) == '@') {
                return UIUtils.createFontGlyph(icon.substring(1), size);
            } else {
                ImageView imageView = new ImageView(icon);
                imageView.setFitHeight(size);
                imageView.setFitWidth(size);
                return imageView;
            }
        }
        return null;
    }

    @Override
    public PluginInfo getPluginInfo() {
        return pluginInfo;
    }

    @Override
    public boolean isFav() {
        return pluginInfo.isFav();
    }

    @Override
    public void close() {
        if (controller != null && controller instanceof Closeable) {
            try {
                ((Closeable) controller).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
